package log

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"os"
	"time"
)

var (
	LogSavePath = "runtime/logs/"
	LogSaveName = "log"
	LogFileExt = "log"
	TimeFormat = "20060102"
)

func init() {
	go LogTimer()
}

// getLogFilePath get the log file save path
func getLogFilePath() string {
	return fmt.Sprintf("%s", LogSavePath)
}

// getLogFileName get the save name of the log file
func getLogFileName() string {
	return fmt.Sprintf("%s%s.%s",
		LogSaveName,
		time.Now().Format(TimeFormat),
		LogFileExt,
	)
}

/*
	每天零点删除日志，并创建新一天的日志文件
*/
func LogTimer() {
	c := cron.New(cron.WithSeconds())
	spec := "0 0 0 * * ?"
	c.AddFunc(spec, func() {
		Setup()
		file := fmt.Sprintf("runtime/logs/%s%s.%s", "log", time.Now().AddDate(0,0,-13).Format("20060102"), "log")
		err := os.Remove(file)
		if err != nil {
			Warn(err.Error())
		} else {
			Info("已删除日志文件" + file)
		}
	})
	c.Start()
	defer c.Stop()
	select{}
}
